import { login, logout, queryAuth } from '@/api/user'
import { queryInfo } from '@/api/webviews'
import { getToken, setToken, removeToken, setUserInfo, setLuYou, getLuYou, removeLuYou } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { columnqueryAll } from '@/api/webpage'
import store from '@/store'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: '',
  luyou: getLuYou()
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_LUYOU: (state, luyou) => {
    state.luyou = luyou
  }

}

const actions = {
  // user login
  async login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: username, password: password }).then(async(response) => {
        const { data } = response
        commit('SET_TOKEN', data[0])
        commit('SET_ROLES', data[0])
        if (data[0] != 'admin') {
          queryAuth().then(async(result) => {
            if (JSON.stringify(result.data) != '[]') {
              commit('SET_LUYOU', JSON.stringify(result.data))
              setLuYou(JSON.stringify(result.data))
              const roles = ''
              const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
              router.addRoutes(accessRoutes)
            } else {
              commit('SET_LUYOU', '')
              setLuYou('')
              const roles = ''
              const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
              router.addRoutes(accessRoutes)
            }
          })
        } else {
          const data = {
            name: '',
            code: '',
            parentId: ''
          }
          columnqueryAll(data).then(async(result) => {
            if (result.code == 0) {
              const array = []
              result.data.forEach(item => {
                if (item.parentId == null) {
                  array.push({
                    path: item.path,
                    name: item.name
                  })
                }
              })
              commit('SET_LUYOU', JSON.stringify(array))
              setLuYou(JSON.stringify(array))
              const roles = ''
              const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
              router.addRoutes(accessRoutes)
            }
          })
        }

        setToken(data)
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_ROLES', getToken())
    })
  },
  async getUser({ commit, state }) {
    return new Promise((resolve, reject) => {
      queryInfo().then((res) => {
        setUserInfo(JSON.stringify(res.data))
        resolve(res)
      })
      queryAuth().then(async(result) => {
        if (JSON.stringify(result.data) != '[]') {
          console.log('🚀 ~ file: user.js:110 ~ queryAuth ~ result:', result)
          commit('SET_LUYOU', JSON.stringify(result.data))
          setLuYou(JSON.stringify(result.data))
        }
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        removeLuYou()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
